package com.charley.icloud.admin.webapps.sysdept.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.charley.icloud.admin.webapps.sysdept.pojo.entity.SysDeptDO;
import com.charley.icloud.admin.webapps.sysdept.pojo.request.SysDeptQuery;
import com.charley.icloud.admin.webapps.sysdept.service.SysDeptService;
import com.charley.icloud.common.constants.SystemNumberConstants;
import com.charley.icloud.common.response.code.BackAdminSysCode;
import com.charley.icloud.common.response.result.HttpResponseResult;
import com.charley.icloud.common.response.result.HttpResponseResultFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sys/dept")
@Tag(name = "机构控制器")
public class SysDeptController {

    @Resource
    private SysDeptService sysDeptService;

    @PostMapping(value = "/save")
    @Operation(summary = "保存机构", description = "后台管理系统")
    public HttpResponseResult save(@RequestBody SysDeptQuery query) {
        if (query != null) {
            SysDeptDO record = new SysDeptDO();
            BeanUtil.copyProperties(query, record, CopyOptions.create().ignoreCase().ignoreNullValue());
            return HttpResponseResultFactory.success(sysDeptService.save(record));
        }
        return HttpResponseResultFactory.fail(BackAdminSysCode.ICLOUD_SYSTEM_ERROR_CODE, "请求参数不正确...");
    }

    @PostMapping(value = "/delete")
    @Operation(summary = "删除机构", description = "后台管理系统")
    public HttpResponseResult delete(@RequestBody List<SysDeptQuery> queries) {
        if (queries != null && queries.size() > SystemNumberConstants.SYSTEM_NUMBER_INTEGER_ZERO) {
            List<SysDeptDO> records = new ArrayList<>();
            for (SysDeptQuery query : queries) {
                SysDeptDO sysDeptDO = new SysDeptDO();
                BeanUtil.copyProperties(query, sysDeptDO, CopyOptions.create().ignoreCase().ignoreNullValue());
                records.add(sysDeptDO);
            }
            return HttpResponseResultFactory.success(sysDeptService.delete(records));
        }
        return HttpResponseResultFactory.fail(BackAdminSysCode.ICLOUD_SYSTEM_ERROR_CODE, "网络异常，删除失败，请重试...");
    }

    @GetMapping(value="/findTree")
    @Operation(summary = "查询机构树", description = "后台管理系统")
    public HttpResponseResult findTree() {
        return HttpResponseResultFactory.success(sysDeptService.findTree());
    }

}
